local base = _G
module("gui")

ImageG = {}
ImageGMT = { __index = ImageG }

base.setmetatable(ImageG, { __index = ObjectG })

ImageG.create = function(x, y, image, width, height, mt)
  if image then
    width = width or image.width
    height = height or image.height
  end
  width = width or 50
  height = height or 50

  local self = Object(x, y, width, height, mt or ImageGMT)

  self.is_down = false
  self:set_image(image)
  self.offsetx = 0
  self.offsety = 0

  return self
end

ImageG.destroy = function(self)
  self:set_image(nil)
  self:set_down_image(nil)
  self.is_down = nil

  ObjectG.destroy(self)
end

ImageG.set_image = function(self, image, sx, sy, w, h)
  self.image = image
  self.imagesx = sx
  self.imagesy = sy
  self.imagew = w
  self.imageh = h
end

ImageG.set_down_image = function(self, image, sx, sy, w, h)
  self.dimage = image
  self.dimagesx = sx
  self.dimagesy = sy
  self.dimagew = w
  self.dimageh = h
end

-- handle mouse input
ImageG.mouse_press = function(self, button, x, y)
  self.is_down = true
end

ImageG.mouse_release = function(self, button, x, y)
  self.is_down = false
  if self:test_point(x, y) == true then
    self:on_click()
  end
end

ImageG.redraw = function(self, dt)
  local c = self.node.canvas
  c:clear()

  -- draw the image
  local image = self.image
  if self.is_down == true and self.dimage then
    image = self.dimage
  end
  if image then
    local x = self.width/2 + self.offsetx
    local y = -self.height/2 + self.offsety

    local w, h = self.imagew, self.imageh
    local sx, sy = self.imagesx, self.imagesy
    if self.is_down == true and self.dimage then
      w, h = self.dimagew, self.dimageh
      sx, sy = self.dimagesx, self.dimagesy
    end
    if w and h and sx and sy then
      c:set_source_subimage(image, sx, sy, w, h, x, y)
    else
      c:set_source_image(image, x, y)
    end
    c:paint()
  end
end

ImageG.update = function(self, dt)
  self:redraw(dt)
end

-- events
ImageG.on_click = function(self)
  
end
  
Image = ImageG.create